/********************************************************************************
 *	Copyright 2011 Gerry Weirich
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *	$Id$
 ********************************************************************************/

package ch.rgw.cybert.persist;

import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;
import org.ektorp.http.HttpClient;
import org.ektorp.http.StdHttpClient;
import org.ektorp.impl.StdCouchDbConnector;
import org.ektorp.impl.StdCouchDbInstance;

/**
 * To simplify handling with ektorp, these classes are written in Java.
 * @author gerry
 *
 */
public class Connector {
	private static CouchDbConnector db;
	
	public static CouchDbConnector createCouchDbConnector(String url, String name) {
		if(url==null){
			url="localhost";
		}
		StdHttpClient.Builder builder=new StdHttpClient.Builder().port(5984);

		if(url.contains(",")){
			String[] cDetails=url.split(",");
			url=cDetails[0];
			builder=builder.username(cDetails[1]).password(cDetails[2]);
		}

		HttpClient httpClient = builder.host(url).build();

		CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
		db = new StdCouchDbConnector(name, dbInstance);

		db.createDatabaseIfNotExists();
		return db;
	}
	
	public static CouchDbConnector getConnector(){
		return db;
	}
}
